package robotlearn

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const sendUrl = "http://www.tuling123.com/openapi/api"
const sendKey = "be5fe81746be4265a8b78dcea8bcb419"

type Question struct {
	Key    string `json:"key"`    //appkey
	Userid string `json:"userid"` // 用户id
	Info   string `json:"info"`   //用户消息
}

type Answer struct {
	Code  int    `json:"code"` //返回值
	Text  string `json:"text"` //文本内容
	Url   string `json:"url"`  //返回链接
	Newss []News `json:"list"` //返回新闻
}

type News struct {
	Article string `json:"article"`   //新闻标题
	Source  string `json:"source"`    //来源
	Name    string `json:"name"`      //菜谱类名称
	Info    string `json:"info"`      //编辑后台
	Icon    string `json:"icon"`      //标题
	Url     string `json:"detailurl"` //详情链接
}

func Say(con string) (*Answer, error) {
	question := &Question{Key: sendKey, Userid: "1111", Info: con}
	b, err := json.Marshal(question)
	if err != nil {
		return nil, err
	}
	body := bytes.NewBuffer([]byte(b))
	req, _ := http.NewRequest("POST", sendUrl, body)
	req.Header.Set("Content-Type", "application/json")
	client := http.DefaultClient
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("网络错误", err)
		return nil, err
	}
	retbody := resp.Body
	defer retbody.Close()
	if resp.StatusCode != 200 {
		fmt.Errorf("HTTP Response Error %d\n", resp.StatusCode)
		return nil, nil
	}
	retbodyr, _ := ioutil.ReadAll(retbody)
	answer := &Answer{}
	json.Unmarshal(retbodyr, &answer)
	return answer, nil
}
